package com.adwin.addcoin.utils

import android.content.Context
import android.os.Build
import android.text.TextUtils
import com.adwin.addcoin.AddCoinApplication
import com.adwin.addcoin.BuildConfig
import com.adwin.addcoin.repository.db.RoomUtils
import com.adwin.addcoin.repository.db.RtRepostData
import com.google.gson.Gson
import kotlinx.coroutines.GlobalScope
import org.json.JSONArray
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.TimeZone
import java.util.UUID
import kotlin.math.abs

/**
 * 埋点
 */
suspend fun Context.installRepost(event:String,obj:JSONObject = JSONObject()){
    val data = RtRepostData();
    data.event_name = "adcoin_$event"
    data.account_id = DevicesUtils.map[DevicesUtils.gaidLable] as String
    data.imei = DevicesUtils.map[DevicesUtils.imei] as String
    data.manufacturer = DevicesUtils.map[DevicesUtils.manufacturerName] as String
    data.os_version = Build.VERSION.RELEASE
    data.bundle_id = BuildConfig.APPLICATION_ID
    data.brand = Build.BRAND
    data.os = "android"
    data.type = "track"
    data.app_version = DevicesUtils.map[DevicesUtils.versionName] as String
    data.system_language = DevicesUtils.map[DevicesUtils.language] as String
    data.log_id = UUID.randomUUID().toString()
    data.app_id = BuildConfig.AppId
    data.properties = obj.toString()
    data.zone_offset = abs(Date().timezoneOffset / 60)
    data.time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(Date())
    RoomUtils.getInstance(this).install(data)
}

suspend fun Context.getRePost():JSONArray{
    val stringData = JSONArray()
    val number = this.getRepostNumber()
    RoomUtils.getInstance(this).getRePost(number).forEach {
       val post =  Gson().toJson(it)?:""
        val obt = JSONObject(post)
        val properties = obt.optString("properties")
        val jsonObject = if (!TextUtils.isEmpty(properties)){
            JSONObject(properties)
        }else{
            JSONObject()
        }
        obt.remove("properties")
        obt.remove("uid")
        jsonObject.put("gaid",AddCoinApplication.gaid)
        obt.put("properties",jsonObject)
        stringData.put(obt)
    }
    return stringData

}